package com.yunmaozj.tools.lock.annotations;

import com.yunmaozj.tools.lock.interceptor.BusinessIdGenerator;
import com.yunmaozj.tools.lock.interceptor.DistributedLockAttribute;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.annotation.AnnotationUtils;

import java.lang.reflect.AnnotatedElement;

/**
 * @author 钟明宏
 * @version V1.0
 * @date 2021-08-30 13:49
 **/
public class DistributedLockAnnotationParser {

    public boolean isCandidateClass(Class<?> targetClass) {
        return AnnotationUtils.isCandidateClass(targetClass, DistributedLock.class);
    }

    public DistributedLockAttribute parseTransactionAnnotation(AnnotatedElement element) {
        AnnotationAttributes attributes = AnnotatedElementUtils.findMergedAnnotationAttributes(
                element, DistributedLock.class, false, false);
        if (attributes == null) {
            return null;
        }
        return parseTransactionAnnotation(attributes);
    }

    protected DistributedLockAttribute parseTransactionAnnotation(AnnotationAttributes annotationAttributes) {
        DistributedLockAttribute distributedLockAttribute = new DistributedLockAttribute();
        Class<? extends BusinessIdGenerator> businessIdGenerator = annotationAttributes.getClass("businessIdGenerator");
        try {
            distributedLockAttribute.setBusinessIdGenerator(businessIdGenerator.newInstance());
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return distributedLockAttribute;
    }
}
